package com

import (
	"fmt"
	"gim-server/config"
	"gim-server/errs"
	"gim-server/sdk"
	"gim-server/utils"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

type GenCosUploadUrlArgs struct {
	Prefix string `json:"prefix" binding:"required"`
	Mime   string `json:"mime" binding:"required"`
}

type GenCosUploadUrlDto struct {
	Key string `json:"key"`
	Url string `json:"url"`
}

func genCosUploadUrl(ctx *gin.Context) {
	args := new(GenCosUploadUrlArgs)
	if err := ctx.ShouldBindJSON(args); err != nil {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiParamsErr,
			Err:  err,
		})
		return
	}
	var key string
	cfg := config.GetCfg()
	fileName := fmt.Sprintf("%s.%s", uuid.New().String(), args.Mime)
	if args.Prefix == "image" {
		key = cfg.CosImageFolder + fileName
	} else if args.Prefix == "video" {
		key = cfg.CosVideoFolder + fileName
	} else if args.Prefix == "audio" {
		key = cfg.CosAudioFolder + fileName
	} else {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiSrvErr,
			Msg:  "无效前缀",
		})
		return
	}
	url, err := sdk.GenUploadUrl(key)
	if err != nil {
		utils.ERR(ctx, &utils.ErrArgs{
			Code: errs.ApiSrvErr,
			Err:  err,
		})
		return
	}
	utils.SUC(ctx, &GenCosUploadUrlDto{
		Key: key,
		Url: url,
	})
}
